#!/usr/bin/env python3
"""
生成测试数据脚本
"""
import sys
import os
from datetime import datetime, timedelta
import random

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from app import create_app
from app.extensions import db
from app.models.customer import Customer
from app.models.staff import Staff, StaffProject
from app.models.negotiation import Negotiation
from app.models.attendance import Attendance
from app.models.associations import CustomerStaff
from app.models.user import User

def generate_test_data():
    """生成测试数据"""
    app = create_app()
    
    with app.app_context():
        print("开始生成测试数据...")
        
        # 清理现有数据（可选）
        print("清理现有数据...")
        Attendance.query.delete()
        CustomerStaff.query.delete()
        StaffProject.query.delete()
        Negotiation.query.delete()
        Customer.query.delete()
        Staff.query.delete()
        # 保留用户数据，不删除
        
        # 生成客户数据
        print("生成客户数据...")
        customers_data = [
            {'name': '张明华', 'project_number': 'PRJ001', 'gender': '男', 'industry': '科技', 'contact_person': '张明华', 'contact_phone': '13800138001'},
            {'name': '李小红', 'project_number': 'PRJ002', 'gender': '女', 'industry': '金融', 'contact_person': '李小红', 'contact_phone': '13800138002'},
            {'name': '王大力', 'project_number': 'PRJ003', 'gender': '男', 'industry': '制造业', 'contact_person': '王大力', 'contact_phone': '13800138003'},
            {'name': '陈美丽', 'project_number': 'PRJ004', 'gender': '女', 'industry': '教育', 'contact_person': '陈美丽', 'contact_phone': '13800138004'},
            {'name': '刘建国', 'project_number': 'PRJ005', 'gender': '男', 'industry': '医疗', 'contact_person': '刘建国', 'contact_phone': '13800138005'},
            {'name': '赵雅芳', 'project_number': 'PRJ006', 'gender': '女', 'industry': '零售', 'contact_person': '赵雅芳', 'contact_phone': '13800138006'},
            {'name': '孙海洋', 'project_number': 'PRJ007', 'gender': '男', 'industry': '物流', 'contact_person': '孙海洋', 'contact_phone': '13800138007'},
            {'name': '周文静', 'project_number': 'PRJ008', 'gender': '女', 'industry': '房地产', 'contact_person': '周文静', 'contact_phone': '13800138008'},
            {'name': '吴志强', 'project_number': 'PRJ009', 'gender': '男', 'industry': '汽车', 'contact_person': '吴志强', 'contact_phone': '13800138009'},
            {'name': '郑春花', 'project_number': 'PRJ010', 'gender': '女', 'industry': '农业', 'contact_person': '郑春花', 'contact_phone': '13800138010'},
            {'name': '黄国庆', 'project_number': 'PRJ011', 'gender': '男', 'industry': '能源', 'contact_person': '黄国庆', 'contact_phone': '13800138011'},
            {'name': '林小玲', 'project_number': 'PRJ012', 'gender': '女', 'industry': '通讯', 'contact_person': '林小玲', 'contact_phone': '13800138012'},
            {'name': '徐正义', 'project_number': 'PRJ013', 'gender': '男', 'industry': '建筑', 'contact_person': '徐正义', 'contact_phone': '13800138013'},
            {'name': '冯丽娜', 'project_number': 'PRJ014', 'gender': '女', 'industry': '娱乐', 'contact_person': '冯丽娜', 'contact_phone': '13800138014'},
            {'name': '丁世杰', 'project_number': 'PRJ015', 'gender': '男', 'industry': '软件', 'contact_person': '丁世杰', 'contact_phone': '13800138015'},
        ]
        
        for customer_data in customers_data:
            start_date = datetime.now().date() - timedelta(days=random.randint(30, 365))
            end_date = start_date + timedelta(days=random.randint(90, 300)) if random.choice([True, False]) else None
            
            customer = Customer(
                name=customer_data['name'],
                project_number=customer_data['project_number'],
                gender=customer_data['gender'],
                start_date=start_date,
                end_date=end_date,
                suitable_manager=random.choice(['张三', '李四', '王五', '赵六']),
                industry=customer_data['industry'],
                contact_person=customer_data['contact_person'],
                contact_phone=customer_data['contact_phone'],
                contact_email=f"{customer_data['name'].lower()}@example.com",
                is_cooperation_ended=end_date is not None and end_date < datetime.now().date()
            )
            customer.calculate_cooperation_days()
            db.session.add(customer)
        
        # 生成员工数据
        print("生成员工数据...")
        staff_data = [
            {'name': '张三', 'project_name': '智能制造项目', 'position': '组长', 'phone': '13700137001'},
            {'name': '李四', 'project_name': '金融科技项目', 'position': '副组长', 'phone': '13700137002'},
            {'name': '王五', 'project_name': '教育信息化项目', 'position': '成员', 'phone': '13700137003'},
            {'name': '赵六', 'project_name': '医疗健康项目', 'position': '组长', 'phone': '13700137004'},
            {'name': '钱七', 'project_name': '电商平台项目', 'position': '成员', 'phone': '13700137005'},
            {'name': '孙八', 'project_name': '物流管理项目', 'position': '副组长', 'phone': '13700137006'},
            {'name': '周九', 'project_name': '房产管理项目', 'position': '成员', 'phone': '13700137007'},
            {'name': '吴十', 'project_name': '汽车销售项目', 'position': '组长', 'phone': '13700137008'},
            {'name': '郑十一', 'project_name': '农业管理项目', 'position': '成员', 'phone': '13700137009'},
            {'name': '王十二', 'project_name': '能源监控项目', 'position': '副组长', 'phone': '13700137010'},
            {'name': '赵十三', 'project_name': '通讯服务项目', 'position': '组长', 'phone': '13700137011'},
            {'name': '钱十四', 'project_name': '建筑设计项目', 'position': '成员', 'phone': '13700137012'},
            {'name': '孙十五', 'project_name': '娱乐平台项目', 'position': '副组长', 'phone': '13700137013'},
            {'name': '周十六', 'project_name': '软件开发项目', 'position': '组长', 'phone': '13700137014'},
        ]
        
        for staff_info in staff_data:
            staff = Staff(
                name=staff_info['name'],
                project_name=staff_info['project_name'],
                position=staff_info['position'],
                specific_position=f"{staff_info['position']}职务",
                project_level=random.choice(['A级', 'B级', 'C级']),
                phone=staff_info['phone'],
                email=f"{staff_info['name'].lower()}@company.com",
                is_general_manager=staff_info['position'] == '组长' and random.choice([True, False]),
                project_create_time=datetime.now() - timedelta(days=random.randint(30, 200))
            )
            db.session.add(staff)
        
        # 提交员工和客户数据
        db.session.commit()
        
        # 获取所有客户和员工
        customers = Customer.query.all()
        staff_list = Staff.query.all()
        
        # 生成商谈记录数据
        print("生成商谈记录数据...")
        categories = ['线上合作商谈', '线下合作商谈']
        projects = ['智能制造项目', '金融科技项目', '教育信息化项目', '医疗健康项目', '电商平台项目']
        
        for i in range(20):  # 生成20条商谈记录
            customer = random.choice(customers)
            
            # 随机选择1-3个负责人
            selected_staff = random.sample(staff_list, random.randint(1, 3))
            staff_names = '、'.join([s.name for s in selected_staff])
            
            # 生成随机时间
            start_time = datetime.now() - timedelta(days=random.randint(1, 30), 
                                                   hours=random.randint(8, 17), 
                                                   minutes=random.randint(0, 59))
            end_time = start_time + timedelta(hours=random.randint(1, 4), 
                                            minutes=random.randint(0, 59))
            duration_minutes = int((end_time - start_time).total_seconds() / 60)
            
            negotiation = Negotiation(
                customer_name=customer.name,
                project_number=customer.project_number,
                category=random.choice(categories),
                staff_names=staff_names,
                project_name=random.choice(projects),
                start_time=start_time,
                end_time=end_time,
                duration_minutes=duration_minutes,
                notes=f"关于{customer.name}的商谈记录，讨论了合作细节和具体方案。",
                is_cross_project=len(selected_staff) > 1
            )
            db.session.add(negotiation)
        
        # 提交商谈记录数据
        db.session.commit()
        
        # 生成员工项目关联数据
        print("生成员工项目关联数据...")
        staff_list = Staff.query.all()
        additional_projects = ['数据分析项目', '人工智能项目', '区块链项目', '云计算项目', '大数据项目']
        
        for staff in staff_list:
            # 为每个员工随机关联1-2个额外项目
            extra_projects = random.sample(additional_projects, random.randint(1, 2))
            for project in extra_projects:
                staff_project = StaffProject(
                    staff_id=staff.id,
                    project_name=project,
                    project_level=random.choice(['省一级', '市一级', '区县一级']),
                    position_in_project=random.choice(['组长', '副组长', '成员']),
                    specific_position_in_project=f"{project}负责人",
                    is_active=True,
                    role=random.choice(['开发', '测试', '运维', '产品'])
                )
                db.session.add(staff_project)
        
        # 生成客户-员工关联数据
        print("生成客户-员工关联数据...")
        customers = Customer.query.all()
        staff_list = Staff.query.all()
        
        for customer in customers:
            # 为每个客户随机分配2-4个负责人
            assigned_staff = random.sample(staff_list, random.randint(2, 4))
            for staff in assigned_staff:
                customer_staff = CustomerStaff(
                    customer_id=customer.id,
                    staff_id=staff.id,
                    project_name=staff.project_name,
                    is_active=True,
                    relationship_type=random.choice(['主要负责', '协助负责', '技术支持'])
                )
                db.session.add(customer_staff)
        
        # 生成考勤记录数据
        print("生成考勤记录数据...")
        staff_list = Staff.query.all()
        
        # 生成最近30天的考勤记录
        for day_offset in range(30):
            date = datetime.now().date() - timedelta(days=day_offset)
            
            # 跳过周末
            if date.weekday() >= 5:  # 5=周六, 6=周日
                continue
                
            for staff in staff_list:
                # 85%的概率员工会上班
                if random.random() < 0.85:
                    # 生成上班时间 (8:00-10:00之间)
                    check_in_hour = random.randint(8, 9)
                    check_in_minute = random.randint(0, 59)
                    check_in_time = datetime.combine(date, datetime.min.time().replace(hour=check_in_hour, minute=check_in_minute))
                    
                    # 生成进门记录
                    attendance_in = Attendance(
                        staff_name=staff.name,
                        staff_id=staff.id,
                        project_name=staff.project_name,
                        event_type='进门',
                        event_time=check_in_time,
                        is_resident=random.choice([True, False]),
                        date=date,
                        check_in_time=check_in_time.time(),
                        is_late=check_in_hour >= 9,
                        status='正常' if check_in_hour < 9 else '迟到'
                    )
                    db.session.add(attendance_in)
                    
                    # 生成下班时间 (17:00-20:00之间)
                    check_out_hour = random.randint(17, 19)
                    check_out_minute = random.randint(0, 59)
                    check_out_time = datetime.combine(date, datetime.min.time().replace(hour=check_out_hour, minute=check_out_minute))
                    
                    # 计算工作时长
                    work_duration = check_out_time - check_in_time
                    work_hours = work_duration.total_seconds() / 3600
                    
                    # 生成出门记录
                    attendance_out = Attendance(
                        staff_name=staff.name,
                        staff_id=staff.id,
                        project_name=staff.project_name,
                        event_type='出门',
                        event_time=check_out_time,
                        is_resident=random.choice([True, False]),
                        date=date,
                        check_out_time=check_out_time.time(),
                        work_hours=work_hours,
                        is_early_leave=check_out_hour < 18,
                        status='正常' if check_out_hour >= 18 else '早退'
                    )
                    db.session.add(attendance_out)
                else:
                    # 生成请假记录
                    absence = Attendance(
                        staff_name=staff.name,
                        staff_id=staff.id,
                        project_name=staff.project_name,
                        event_type='请假',
                        event_time=datetime.combine(date, datetime.min.time().replace(hour=9)),
                        date=date,
                        status=random.choice(['请假', '病假', '事假']),
                        notes=random.choice(['个人事务', '身体不适', '家庭事务', '培训学习'])
                    )
                    db.session.add(absence)
        
        # 提交所有数据
        db.session.commit()
        
        # 统计生成的数据
        customer_count = Customer.query.count()
        staff_count = Staff.query.count()
        negotiation_count = Negotiation.query.count()
        attendance_count = Attendance.query.count()
        staff_project_count = StaffProject.query.count()
        customer_staff_count = CustomerStaff.query.count()
        
        print(f"数据生成完成！")
        print(f"- 客户数据: {customer_count} 条")
        print(f"- 员工数据: {staff_count} 条")
        print(f"- 商谈记录: {negotiation_count} 条")
        print(f"- 考勤记录: {attendance_count} 条")
        print(f"- 员工项目关联: {staff_project_count} 条")
        print(f"- 客户员工关联: {customer_staff_count} 条")

if __name__ == '__main__':
    generate_test_data()

